/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.jmh.benchmark.counter.impl;

import java.util.concurrent.Semaphore;

import me.ijleex.jmh.benchmark.counter.Counter;

/**
 * SemaphoreCounter.
 *
 * @author liym
 * @since 2020-05-27 13:02 新建
 */
public class SemaphoreCounter implements Counter {

    private final Semaphore semaphore;

    private long counter;

    /**
     * @param fair 是否使用公平锁
     */
    public SemaphoreCounter(boolean fair) {
        this.semaphore = new Semaphore(1, fair);
    }

    @Override
    public void increment() {
        try {
            this.semaphore.acquire();
            ++this.counter;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } finally {
            this.semaphore.release();
        }
    }

    @Override
    public long getCount() {
        try {
            this.semaphore.acquire();
            return this.counter;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } finally {
            this.semaphore.release();
        }
    }

}
